# %%

from strategy_mode import dataLoader, str_cal, Trading, TradingRules, TradingLoop
from live_cals import LoadingLoop, futuredays, Strategy_Main
from live_cals import polyfitlize_2 as polyfitlize
from live_plot import Main_plot
from strategy_mode import WAVE
from OtherTools.filetool import FileCheck
from strategy_mode import TradingStrategy_sum_03 as Strgs
from DataTools import datatool
from OtherTools import filetool
import json
import math
import pandas as pd
import gc
import os
import re

from rich import print

# from rich.console import Console
# from rich.syntax import Syntax


def MainCalinLoop(
    df,
    Ma_Day_List=[3, 5, 8],
    pre=48,
    distionSearchDay=10,
    MainLines_CountStartGroup=1,
    line_Pares=2,
    printLens=60,
    keyls=["low", "open", "close", "high"],
):
    df = str_cal.MAsBuliderMAIN(df, keyls, Ma_Day_List, shift=False)  # 计算各种MA，MA布尔值等等
    df = str_cal.Macount(df, Ma_Day_List)
    df = str_cal.Ma_order_count(df, Ma_Day_List, keyls)
    print("ma_done".center(printLens, " "))

    # )  # 计算卖出信号，红蓝占比
    gc.collect()
    df = str_cal.BollFastSum_All(
        df, keyls, "_by%", sub_Key="", Ma_Day_List=Ma_Day_List, drop=False
    )

    df = df.fillna(0)
    pre_g = re.findall("\d*", pre)
    if pre_g != ["", ""]:
        gap = 240 / int(pre)
    else:
        if "D" in pre.upper():
            gap = 8
        if "M" in pre.upper() or "Y" in pre.upper():
            gap = 1
    fillin = int(gap * 4)
    gap = int(gap)
    gap2 = (1 - math.log(gap) * 0.1) * 1.2
    cat = "All_by%_sum_{}_rolling".format(fillin)
    df.loc[:, "T_" + cat] = df["All_by%_sum"].rolling(fillin).mean()
    df.loc[:, "TH_" + cat.format(fillin)] = (
        df["T_" + cat] + df["All_by%_sum"].rolling(fillin).std() * gap2
    )
    df.loc[:, "TL_" + cat.format(fillin)] = (
        df["T_" + cat] - df["All_by%_sum"].rolling(fillin).std() * gap2
    )

    cat = "All_sort_{}_rolling".format(int(fillin))
    df.loc[:, "T_" + cat] = df["All_sort"].rolling(fillin).mean()

    gc.collect()

    return df


def range_gap(pre):
    pre_g = re.findall("\d*", pre)
    if pre_g != ["", ""]:
        gap = int(240 / int(pre))
    else:
        gap = 20
    return gap


def Main_cal(
    pre="15",
    code="300999",
    Cutting_start_date="2014-01-01",
    future_days=5,
    GroupOfLines=4,
    dirDic={
        "Main": "D:/StockDatas/",
        "basic": "basic/",
        "daily": "163_Daily_Bar/",
        "report": "Reports/",
        "temp": "temp/",
        "ticker": "History_ticker/",
        "mins": "History_mins/",
    },
):

    temppath = dirDic["Main"] + dirDic["temp"] + "{}_{}.csv".format(code, pre)
    print("code: {} pre: {}".format(code, pre).center(60, " "))

    chack = 0

    Ma_Day_List = WAVE.Waves(GroupOfLines - 1)
    line_Pares = len(Ma_Day_List) / (GroupOfLines)
    Ma_Day_List.sort()
    Ma_Day_List_Max = max(Ma_Day_List)

    stock_details, df = LoadingLoop.LoadingLoop(
        code, pre=pre, Cutting_start_date=Cutting_start_date
    )
    print(
        "post day:{} area:{} rows:{}".format(
            stock_details[0], "SH" if stock_details[1] == 0 else "SZ", df.shape[0]
        ).center(60, " ")
    )

    print("{} >> {}".format(df.date.iloc[0], df.date.iloc[-1]).center(60, " "))

    df.drop("index", axis=1, inplace=True)
    df = Strategy_Main.Strategy_Main(
        df,
        pre=pre,
        Ma_Day_List=Ma_Day_List,
        GroupOfLines=GroupOfLines,
        keyls=["close", "low", "high", "open", "Avg"],
    )
    gap = range_gap(pre)
    df = futuredays.futuredays(df, number_of_days=future_days, gap=gap * 2, pre=pre)
    df = polyfitlize.polyfitlize(df, "Avg", gap=gap, pre=pre)

    df.to_csv(temppath, index=False)
    print("done {}".format(temppath).center(60, " "))
    print()
    gc.collect()
    return df, stock_details


def remove_columns(
    col_les=[],
    col_key=["polynomial_X_", "Q_", "Avg_ma_"],
):
    temp = col_les.copy()
    for key in col_key:
        for col in col_les:
            if col.startswith(key):
                temp.remove(col)
    return temp


def Strategy_Main_3(
    Strgs,
    code="300999",
    pre="5",
    simulation_type="run",
    AvableCash=100000,
    tradePersentDic={"x1": 1},
    fees_Persent=0.0035,
    Cutting_start_date="2018-11-10",
    GroupOfLines=3,
    MainLines_CountStartGroup=1,
    printLens=60,
    keyls=["close", "low", "high", "open", "Avg"],
    dirDic={
        "Main": "D:/StockDatas/",
        "basic": "basic/",
        "daily": "163_Daily_Bar/",
        "report": "Reports/",
        "temp": "temp/",
        "ticker": "History_ticker/",
        "mins": "History_mins/",
    },
    import_in=False
):

    print(code.center(printLens, "-"))
    # 获取交易日信息
    StockDataDic = datatool.getCodeAndDetail(
        MainPath=dirDic["Main"], subPath=dirDic["basic"]
    )
    Ma_Day_List = str_cal.Waves(GroupOfLines - 1)
    line_Pares = len(Ma_Day_List) / (GroupOfLines)
    count_in = GroupOfLines - MainLines_CountStartGroup
    Ma_Day_List.sort()

    print(str(Ma_Day_List).center(printLens, " "))

    df, stock_details = Main_cal(
        pre=pre,
        code=code,
        Cutting_start_date=Cutting_start_date,
        future_days=5,
        GroupOfLines=4,
    )

    avableCash = AvableCash
    stock_details = StockDataDic[code]
    col_les = df.columns.to_list()

    col_les = remove_columns(
        col_les=col_les,
    )

    _df = df[col_les]
    _df = _df.dropna(axis="index", how="all", subset=["Avg", "low", "open"])
    trading_Log = TradingLoop.TradingMainLoop(
        _df,
        Ma_Day_List,
        Strgs,
        count_in=count_in,
        line_Pares=line_Pares,
        simulation_type=simulation_type,
        tradePersentDic=tradePersentDic,
        AvableCash=avableCash,
        Value_Pread_Mode="M",
    )

    dic = str_cal.resoult(trading_Log, code, AvableCash)
    df = pd.merge(df, trading_Log, on="date", how="left")
    # 输出层
    for key in dic:
        print("--- {}:{} ---".format(key, dic[key]).center(printLens, " "))
    if import_in == False:
        print("- Draw -".center(printLens, " "))
        Main_plot.Main_Candlestick_plot(
            df,
            save_info=[
                code,
                str(round(dic["%_pre_year"] * 100, 2)),
                str(round(dic["%_increase"] * 100, 2)),
            ],
        )

    print("{} {} output".format(code, "logs res").center(printLens, " "))
    gc.collect()
    print(" finish ".center(printLens, "*"))
    print(dic)
    return dic, df


#%%
if __name__ == "__main__":

    strname = "str_sum_01"
    keyls = ["Avg"]
    simulation_type = "run"
    Cutting_start_date = "2020-05-01"
    pre = "5"
    GroupOfLines = 4
    distionSearchDay = 20
    AvableCash = 100000
    pre_g = re.findall("\d*", pre)
    if pre_g != ["", ""]:
        distionSearchDay = int(distionSearchDay * 240 / int(pre_g[0]))

    path = "config_path.json"
    with open(path, mode="r") as f:
        res = f.read()
    dirDic = json.loads(res)
    codel = [
        # "688330",
        # "300894",
        "300999",
        # "601012",
        # "000008",
        # "601398",
        # "600010",
        # "000001",
        # "600605",
        # "600090",
        # "600652",
        # "600086",
        # "600145",
        # "600112",
        # "600083",
        # "600091",
        # "600654",
        # "600146",
        # "600122",
        # "600604",
        # "600601",
        # "000858",
        # "000568",
        # "000596",
        # "000009",
        # "600071",
        # "600080",
        # "000005",
        # "000007",
        # "600603",
        # "600608",
        # "600653",
        # "600084",
        # "002069",
        # "600119",
    ]
    # codel = set(codel)
    res_L = []
    for code in codel:
        dic, df = Strategy_Main_3(
            Strgs,
            pre=pre,
            keyls=keyls,
            simulation_type=simulation_type,
            code=code,
            AvableCash=AvableCash,
            tradePersentDic={"x1": 1},
            fees_Persent=0.0035,
            Cutting_start_date=Cutting_start_date,
            GroupOfLines=GroupOfLines,
            MainLines_CountStartGroup=0,
            printLens=60,
            dirDic=dirDic,
        )
        res_L.append(dic)
    pd.DataFrame(res_L).to_csv("res{}.csv".format(strname))
    # import datetime

    # now = int("".join(datetime.datetime.now().strftime("%H:%M:%S").split(":")))
    # if 0 > now > 630:
    #     os.system("shutdown -s -t 30")
    exit()